package com.roc.web.action.terminal;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblInsInf;
import com.roc.pojo.YsbTermSnStatisticsDetail;
import com.roc.service.IExcelExportService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.Utils;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

/**
 * 云商宝终端统计明细
 * @author lenovo
 *
 */
@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/ysbTermSnStatisDetail")
public class YsbTermSnStatisticsDetailAction extends PaginationBaseAction {

	private static final long serialVersionUID = 1L;

	static Logger logger = LogManager.getLogger(YsbTermSnStatisticsDetailAction.class);

	private YsbTermSnStatisticsDetailSearchCondition searchCondition;

	private List<TblInsInf> orgList = new ArrayList<TblInsInf>();

	private InputStream excelFile;
	
	private String excelName;

	@Autowired
	IPageService pagenitionService;

	@Autowired
	private IExcelExportService iexcelSerivce;
	
	
	
	@Autowired
	IPowerInfoService powerInfoService;
	/**
	 * 云商宝终端统计明细
	 * @Title: init
	 * @return
	 * @throws Exception
	 * @author 
	 * @date: 
	 *
	 */
	@Action(value = "init", results = { @Result(location = "/pages/terminal/YsbTermSnStatisticsDetail.jsp") })
	public String init() throws Exception {
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if( !op.getRoleType().equals(Role.SYSTEM.getCode()) 
				&& !op.getRoleType().equals(Role.O_MANAGER.getCode())
				&& !op.getRoleType().equals(Role.AGENT.getCode())){
			addActionError("此登陆账号没有权限");
			return ERROR;
		}
		org();
		return SUCCESS;
	}
    /**
     *  云商宝终端统计明细
     * @Title: queryTermSnStatisDetail
     * @return
     * @throws Exception
	 * @author 付盼
	 * @date: 2018年3月7日 
     *
     */
	@Action(value = "queryTermSnStatisDetail", results = { @Result(name = "success", location = "/pages/terminal/YsbTermSnStatisticsDetail.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	// 查询终端
	public String queryTermSnStatisDetail() throws Exception {

		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if (searchCondition == null) {
			searchCondition = (YsbTermSnStatisticsDetailSearchCondition) getSearchConditionFromSession();
			if (searchCondition == null) {
				searchCondition = new YsbTermSnStatisticsDetailSearchCondition();
			}
		}
		if( !op.getRoleType().equals(Role.SYSTEM.getCode()) 
				&& !op.getRoleType().equals(Role.O_MANAGER.getCode())
				&& !op.getRoleType().equals(Role.AGENT.getCode())){
			addActionError("此登陆账号没有权限");
			return ERROR;
		}
		try {
			org();
	        searchCondition.setRoleType(op.getRoleType());// 角色
	        searchCondition.setAgentId(String.valueOf(op.getId()));// 当前账号id
			int rows = pagenitionService.countSQL(searchCondition);
	
			searchRsList = pagenitionService.findAllSQL(searchCondition,calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
	
			List<YsbTermSnStatisticsDetail> beanList = new ArrayList<YsbTermSnStatisticsDetail>();
			if (searchRsList != null && searchRsList.size() > 0) {
				Iterator iterator = searchRsList.iterator();
				while (iterator.hasNext()) {
					Object[] obj = (Object[]) iterator.next();
					YsbTermSnStatisticsDetail bean = new YsbTermSnStatisticsDetail();
					
					bean.setMercCode(Constance.Null2EmptyTrim(obj[0]));
					bean.setMercName(Constance.Null2EmptyTrim(obj[1]));
					bean.setPhoneno(Constance.Null2EmptyTrim(obj[2]));
					
					String aff = "";
					if ( !"".equals( Constance.Null2EmptyTrim(obj[3]) ) ){
						aff = Utils.getSnAssefMap().get( Constance.Null2EmptyTrim(obj[3]) );
					}
					bean.setAssefFlag(aff);
					
					bean.setSerialNum(Constance.Null2EmptyTrim(obj[4]));
	
					String brandCode = obj[5] + "";
					String nameCode = obj[6] + "";
					String typeCode = obj[7] + "";
						
					bean.setPosBrand(ConfigMerinfoUtil.getPosBRAND(brandCode));
					bean.setPosName(ConfigMerinfoUtil.getPosMODEL(nameCode , brandCode));
					bean.setPosType(ConfigMerinfoUtil.getTerminalType(typeCode));
					
					beanList.add(bean);
				}
			}
			searchRsList.clear();
			searchRsList.addAll(beanList);
			this.setTotalPage(this.calcuTotalPage(rows));			
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}

		return SUCCESS;
	}

	private void org() {
		try {
			Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
	
			Map<String,String> assefMap = Utils.getSnAssefMap();
			// 去掉 "公司代采"
			assefMap.remove("1");
			getRequest().setAttribute("assefMap", assefMap);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * * 云商宝终端sn统计导出
	 * @Title: excelTermSnStatisDetail
	 * @return
	 * @throws Exception
	 * @author 付盼
	 * @date: 2018年3月7日 
	 *
	 */
	@Action(value = "excelTermSnStatisDetail", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xls", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/error.jsp") })
	public String excelTermSnStatisDetail() throws Exception {

		ByteArrayOutputStream output = new ByteArrayOutputStream();
		String[] headArray = {  "商户号","商户名称", "手机号", "资产类型","终端序列号", "品牌", "型号","机型"};
		String reportName = "云商宝终端统计明细导出";
		try {
			Operators op = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
			if (searchCondition == null) {
				searchCondition = (YsbTermSnStatisticsDetailSearchCondition) getSearchConditionFromSession();
				if (searchCondition == null) {
					searchCondition = new YsbTermSnStatisticsDetailSearchCondition();
				}
			}
			if( !op.getRoleType().equals(Role.SYSTEM.getCode()) 
					&& !op.getRoleType().equals(Role.O_MANAGER.getCode())
					&& !op.getRoleType().equals(Role.AGENT.getCode())){
				addActionError("此登陆账号没有权限");
				return ERROR;
			}
			org();
	        searchCondition.setRoleType(op.getRoleType());// 角色
	        searchCondition.setAgentId(String.valueOf(op.getId()));// 当前账号id
			int rows = pagenitionService.countSQL(searchCondition);
	
			searchRsList = pagenitionService.findAllSQL(searchCondition,0, rows);
	
			searchRsList = dealData(searchRsList, headArray.length);

			if ( null == searchRsList ) {
				searchRsList = new ArrayList<Object>();
			}
			setExcelName(new String(reportName.getBytes(), "ISO8859-1"));

			HSSFWorkbook work = iexcelSerivce.excelExport(reportName,headArray, searchRsList);
			work.write(output);

			byte[] ba = output.toByteArray();
			excelFile = new ByteArrayInputStream(ba);

		} catch (Exception e) {
			logger.info("######导出" + reportName + "失败######");
			addActionError(e.getMessage());
			return ERROR;
		} finally {
			closeOutPut(output);
		}

		return SUCCESS;
	}

	private List<Object> dealData(List<Object> searchRsList, int size)
			throws ServiceException {
		List<Object> searchRsListNew = new ArrayList<Object>();

		if (searchRsList == null || searchRsList.size() == 0) {
			return null;
		}
		Iterator iterator = searchRsList.iterator();
		while (iterator.hasNext()) {
			Object[] obj = (Object[]) iterator.next();
			Object[] objNew = new Object[size];

			objNew[0] = Constance.Null2EmptyTrim(obj[0]);
			objNew[1] = Constance.Null2EmptyTrim(obj[1]);
			objNew[2] = Constance.Null2EmptyTrim(obj[2]);

			String aff = "";
			if ( !"".equals( Constance.Null2EmptyTrim(obj[3]) ) ){
				aff = Utils.getSnAssefMap().get( Constance.Null2EmptyTrim(obj[3]) );
			}
			objNew[3] = aff;

			objNew[4] = Constance.Null2EmptyTrim(obj[4]);
			String brandCode = obj[5] + "";
			String nameCode = obj[6] + "";
			String typeCode = obj[7] + "";
			
			objNew[5] = ConfigMerinfoUtil.getPosBRAND(brandCode);
			objNew[6] = ConfigMerinfoUtil.getPosMODEL(nameCode , brandCode);
			objNew[7] = ConfigMerinfoUtil.getTerminalType(typeCode);
			searchRsListNew.add(objNew);
		}

		return searchRsListNew;

	}

	private void closeOutPut(ByteArrayOutputStream output)
			throws ServiceException {

		try {
			if (output != null) {
				output.flush();
				output.close();
			}
		} catch (IOException e) {
			logger.error("########导出Excel关闭流失败######", e);
			throw new ServiceException("导出Excel关闭流失败！");
		}
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE + "";
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (YsbTermSnStatisticsDetailSearchCondition) getSession().getAttribute(
				SEARCH_SESSION_YSB_SN_STATISTICS_DETAIL);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);

	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_YSB_SN_STATISTICS_DETAIL,
				searchCondition);
	}

	

	public List<TblInsInf> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<TblInsInf> orgList) {
		this.orgList = orgList;
	}

	

	public YsbTermSnStatisticsDetailSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(YsbTermSnStatisticsDetailSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public String getExcelName() {
		return excelName;
	}

	public void setExcelName(String excelName) {
		this.excelName = excelName;
	}



}
